#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>

#define NUM 128  //命令行最长长度
#define CMD_NUM 64  //最可以保存的选项个数
int main()
{
    char command[NUM] = {0};
    char* argv[CMD_NUM] = {NULL};
    while(1)
    {
        //1.打印提示符
        command[0] = 0;//把内容清空
        printf("[who@myhostname mydir]# ");
        fflush(stdout);

        //2.获取命令行
        int n = read(0,command,NUM-1);
        //注意：坑点！！！这里是n-1的位置置为\0,而不是n的位置置为\0
        command[n-1] = '\0'; 
        // fgets(command, NUM, stdin);
        // command[strlen(command) - 1] = '\0';
        
        //3.解析命令行
        const char* sep = " ";
        argv[0] = strtok(command,sep);
        int index = 1;
        while(argv[index++] = strtok(NULL,sep)) ;

        //for test
        // for(int i = 0;argv[i];i++)
        //     printf("argv[%d]:%s\n",i,argv[i]);

        //判断是否执行的是内建命令
        if(strcmp("cd",argv[0]) == 0)
        {
            if(argv[1] != NULL)
                chdir(argv[1]);
            continue;
        }
        //4.创建子进程
        pid_t id = fork();
        if(id == 0) //child
        {
            //5.程序替换
            execvp(argv[0],argv);
            exit(1);
        }

        //parent
        int status = 0;
        int res = waitpid(id,&status,0);
        if(res > 0)
            printf("exit code:%d signal:%d\n",(status>>8)&0xff,status&0x7f);
    }
    return 0;
}